<template>
  <el-upload :action="action" :headers="headers" :http-request="uploadFile">
    <template v-for="(item, key, index) in $slots" :key="index" #[key]>
      <slot :name="key" />
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import type { UploadRequestHandler, UploadRequestOptions } from "element-plus";
import lrz from "lrz";
import type { FileBase64Req } from "@/api/file/types";

import { fileApi } from "@/api/file";
// 上传文件的地址
const action = ref(fileApi.uploadUrl());
// 请求上传的头部
const headers = ref(fileApi.authHeader());

const props = defineProps({
  width: {
    type: Number,
    default: 2048
  },
  quality: {
    type: Number,
    default: 0.8
  },
  fileDir: {
    type: String,
    default: "custom"
  }
});

//自定义文件上传
const uploadFile: UploadRequestHandler = (
  option: UploadRequestOptions
): XMLHttpRequest | Promise<any> => {
  return new Promise((resolve) => {
    lrz(option.file, { width: props.width, quality: props.quality }).then((rst: any) => {
      console.log(rst);
      const base64 = {
        base64: rst.base64,
        fileName: option.file.name,
        contentType: option.file.type,
        fileDir: props.fileDir
      } as FileBase64Req;
      fileApi
        .uploadBase64File(base64)
        .then((res) => {
          resolve(res.data);
          return;
        })
        .catch((err) => {
          console.log(err);
        });
    });
  });
};
</script>
